package com.example.demo.services;

import com.example.demo.dao.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author liyixuan
 * @date 2021年5月11日21:39:10
 */
@Service
public class GetDataServices {
    /*
      每天凌晨1点执行计划任务,更新 allRegionStats成员变量
       allRegionStats成员变量储存着全球新型冠状病毒统计数据
      @throws IOException IO异常
     */
    /*将所有数据封装在date list中，方便获取*/
    private final List<RegionStats> data = new ArrayList<>();

    /**
     * 声明这是一个计划任务
     */
    @Scheduled(cron = "0 0 1 * * *")
    public List<RegionStats> getData() throws IOException {
        /*爬取csv文件*/
        /*
          定义全局变量
          用来储存爬出来的数据
         */
        String dataUrl = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(dataUrl))
                .headers(httpHeaders -> httpHeaders.add("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE"))
                .build();
        ResponseEntity<Resource> responding = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = responding.getBody();

        /*获取csv文件的输入流*/
        assert body != null;
        InputStream input = body.getInputStream();

        /*官方文件要求改写*/
        Reader in = new InputStreamReader(input);
        /*不读取表头,默认第一行为header*/
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
        for (CSVRecord record : records) {
            /*将数据封装在定义的model中*/
            RegionStats states = new RegionStats();
            /*可以获取记录省份/州的值*/
            states.setState(record.get("Province/State"));
            /*可以获取记录国家/地区的值*/
            states.setCountry(record.get("Country/Region"));
            /*获取最新数据和前一天的数据，并将数据转化为integer类型*/
            int latestData = Integer.parseInt(record.get(record.size() - 1));
            int dataFromThePreviousDay = Integer.parseInt(record.get(record.size() - 2));
            states.setLatestTotalCases(latestData);
            /*获取最新的数据变化值*/
            states.setDiffFromPrevDay(latestData - dataFromThePreviousDay);
            data.add(states);
        }
        return data;
    }

    public List<RegionStats> searchDataModel(String address) {
        if (Objects.equals(address, "")) {
            return data;
        }
        /*建立一个新的list，放入查询后的数据*/
        List<RegionStats> resultData = new ArrayList<>();


        for (RegionStats dataModel : data) {
            if (dataModel.getCountry().equals(address) || dataModel.getState().equals(address)) {
                resultData.add(dataModel);
            }
        }
        return resultData;
    }
}
